package lookas.dbaccess;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBFactory {

	private static Connection connection;

	public static Connection getConnection() throws DBException {
		if (connection == null)
			throw new DBException("Connection not opened");
		return connection;
	}

	public static PreparedStatement prepareStatement(String sql)
			throws DBException {

		try {
			return DBFactory.getConnection().prepareStatement(sql);
		} catch (SQLException e) {
			throw new DBException(e);
		}
	}

	public static Connection open(File file) throws DBException {
		if (connection != null)
			return connection;
		if (!file.exists())
			throw new DBException("File " + file.getAbsolutePath()
					+ " doesn't exists.");
		try {
			Class.forName("org.sqlite.JDBC");
			connection = DriverManager.getConnection("jdbc:sqlite:" + file);
			return connection;
		} catch (Exception e) {
			throw new DBException(e);
		}
	}

	public static void close() throws DBException {
		try {
			DBFactory.getConnection().close();
		} catch (SQLException e) {
			throw new DBException(e);
		}
	}
}
